<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\admin\model\Device as DeviceModel;
use app\admin\model\DeviceBind;
use think\Db;
use think\exception\ValidateException;
use think\exception\PDOException;
use Exception;


/**
 * @商品接口
 */
class Device extends Api
{    
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['list', 'info'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];
    

    /**
     * @设备列表
     */
    public function list(DeviceModel $D, $cate_id = null, $orderBy='weigh', $orderType='DESC', $page=1, $pageSize=10)
    {        
        $map['onsellswitch'] = 1;
        if ($cate_id) {
            $map['cate_id'] = $cate_id;
        }
        $list = $D->where($map)
                  ->order($orderBy, $orderType)
                  ->paginate($pageSize);
        
        $listCate = db('devicecate')->column('name','id');
        foreach ($list as $v){
            $v['cate_text'] = $listCate[$v['cate_id']];
        }
        
        $this->success('设备列表', $list);
    }
    
    
    /**
     * @我的设备列表
     */
    public function listMy(DeviceModel $D, $cate_id = null, $orderBy='id', $orderType='DESC', $page=1, $pageSize=10)
    {
        $user = $this->auth->getUserinfo();
        if ($user['devices']) {
            $devicesArr = json_decode($user['devices'], 1);
            if (is_array($devicesArr)) {
                $ids = array_keys($devicesArr);
            }
            $map['id'] = ['in', $ids];
        } else {
            $this->success('设备列表', []);
        }
        
        if ($cate_id && $cate_id!=1) {
            $map['cate_id'] = $cate_id;
        }
        $list = $D->where($map)
                  ->order($orderBy, $orderType)
                  ->paginate($pageSize);
        
        $listCate = db('devicecate')->column('name','id');
        foreach ($list as $v){
            $v['cate_text'] = $listCate[$v['cate_id']];
        }
        
        $this->success('设备列表', $list);
    }
    
    
    /**
     * @设备详情
     * @param DeviceModel $D
     */
    public function info(DeviceModel $D, $id = null) {
        if (!$id) {
            $this->error('设备id不能为空');
        };
        if ($info = $D->get($id)) {
            $this->success('设备详情', $info);
        } else {
            $this->error('设备不存在');
        }
    }
    
    
    /**
     * @添加设备
     */
    public function bind($device_id = null) {
        if (!$device_id) {
            $this->error('设备id不能为空');
        };
        
        $uid = $this->auth->id;
        $user = db('user')->find($uid);
        $device = db('device')->find($device_id);
        if (!$device) {
            $this->error('设备不存在');
        }
        if ($user['devices']) {
            $devicesArr = json_decode($user['devices'], 1);
            if (array_key_exists($device_id, $devicesArr)) {
                $this->error('该设备您已添加，勿须重复！');
            } else {               
                $devicesArr = $devicesArr + [$device_id => date('Y-m-d H:i:s')];
            }
        } else {
            $devicesArr[$device_id] = date('Y-m-d H:i:s');
        }
        
        Db::startTrans();
        try {
            db('user')->where('id', $user['id'])->setField('devices', json_encode($devicesArr));
            //添加绑定日志
            $remark = $user['nickname'] . ' 添加设备：' . $device['name'];
            (new DeviceBind)->allowField(true)->save(['uid'=>$user['id'], 'device_id'=>$device_id, 'remark'=>$remark]);
            
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }    
        
        $this->success('添加设备成功');
    }
    
    
    /**
     * @解绑设备
     */
    public function cancelBind($device_id = null) {
        $uid = $this->auth->id;
        $user = db('user')->find($uid);
        $device = db('device')->find($device_id);
        if ($user['devices']) {
            $devicesArr = json_decode($user['devices'], 1);
            if (array_key_exists($device_id, $devicesArr)) {
                unset($devicesArr[$device_id]);
                Db::startTrans();
                try {
                    db('user')->where('id', $user['id'])->setField('devices', json_encode($devicesArr));
                    //添加绑定日志
                    $remark = $user['nickname'] . ' 删除设备：' . $device['name'];
                    (new DeviceBind)->allowField(true)->save(['uid'=>$user['id'], 'device_id'=>$device_id, 'remark'=>$remark]);
                    
                    Db::commit();
                } catch (ValidateException|PDOException|Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }                
            } else {
                $this->error('您还没添加该设备！');
            }
        } else {
            $this->error('您还没添加任何设备！');
        }
        
        $this->success('删除设备成功');
    }
    
}
